import { getRandomInt } from "@/api"
const actions = {
    selectPlay({ commit }, { list, song }) {
        commit('set_song_list', list)
        commit('set_currentSong', song)
        commit('set_palyStatus', true)
    },
    // 下一首
    nextSong({ state, getters, commit }) {
        var _length = state.songList.length - 1;
        var song;
        if (state.playMode === 'random') {
            var index = getRandomInt(0, _length);
            song = state.songList[index]
        } else {
            var currentIndex = getters.currentIndex + 1
            if (currentIndex > _length) {
                currentIndex = 0
            }
            song = state.songList[currentIndex]
        }
        commit('set_currentSong', song)
        commit('set_palyStatus', true)
    },
    // 上一首
    prevSong({ state, getters, commit }) {
        var _length = state.songList.length - 1;
        var song;
        if (state.playMode === 'random') {
            var index = getRandomInt(0, _length);
            song = state.songList[index]
        } else {
            var currentIndex = getters.currentIndex - 1
            if (currentIndex < 0) {
                currentIndex = _length
            }
            song = state.songList[currentIndex]
        }

        commit('set_currentSong', song)
        commit('set_palyStatus', true)
    },
    // 从歌曲列表中删除歌曲
    deleteSong({ state, getters, commit, dispatch }, index) {
        if (index == getters.currentIndex) {
            dispatch('nextSong')
        }
        var songList = Object.assign([], state.songList);
        songList.splice(index, 1);
        commit('set_song_list', songList);
        if(songList.length ===0){
            commit('set_currentSong',{})
            commit('set_palyStatus',false)
        }
    },
    // 切换音乐
    selectSong({ commit }, song) {
        commit('set_currentSong', song);
        commit('set_palyStatus', true)
    },
    // 清空列表中的音乐
    emptySongList({ commit }) {
        commit('set_song_list', [])
        commit('set_currentSong', {})
        commit('set_palyStatus',false)
    },
    // 将歌曲添加到播放列表
    addSong({ state, getters, commit, dispatch }, song) {
        var [...songList] = state.songList;
        if (getters.currentIndex != -1) {
            songList.splice(getters.currentIndex + 1, 0, song);

        } else {
            songList.push(song)
        }
        commit('set_song_list', songList)
        dispatch('selectSong', song)
    },
    // 切换播放模式
    select_palyMode({state,commit}){
        var next;
        switch (state.playMode) {
            case 'loop':
                next = 'queue'
                break;
            case 'queue':
                next = 'random'
                break;
            case 'random':
                next = 'loop'
                break;
        }
        commit('set_playMode',next)
    }
}

export default actions